package com.lb.uts.util;

import com.lb.uts.exception.RscException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 输出流解析工具类
 */
public class RscResponseUtils {

    /**
     * 解析响应流，转换为字符报文
     *
     * @param httpResponse
     * @param charset
     * @return
     */
    public static String parseResponse(HttpResponse httpResponse, String charset) {
        HttpEntity httpEntity = httpResponse.getEntity();
        try {
            return EntityUtils.toString(httpEntity, charset);
        } catch (IOException e) {
            throw new RscException(e);
        }
    }

    /**
     * 从异步结果中解析响应流，将阻塞异步请求等待响应结果，转为为字符报文
     *
     * @param future
     * @param charset
     * @return
     * @throws InterruptedException 请求被中断，取消访问
     * @throws ExecutionException   请求执行异常
     */
    public static String parseResponse(Future<HttpResponse> future, String charset) {
        HttpResponse httpResponse = null;
        try {
            httpResponse = future.get();
        } catch (InterruptedException e) {
            throw new RscException(e);
        } catch (ExecutionException e) {
            throw new RscException(e);
        }
        return parseResponse(httpResponse, charset);
    }
}